package com.lq.ecoldchain.ui.mine.recommand

import android.arch.lifecycle.MutableLiveData
import android.view.LayoutInflater
import com.lq.ecoldchain.R
import com.lq.ecoldchain.base.view.App
import com.lq.ecoldchain.base.viewmodel.BaseViewModel
import com.lq.ecoldchain.entity.RecommendEntity
import com.lq.ecoldchain.internet.BaseObserver
import com.lq.ecoldchain.util.toast

/*
*2019/1/3 0003  16:11
*function by lq
*/
class RecommendViewModel : BaseViewModel() {
    val code by lazy { MutableLiveData<String>() }
    val list by lazy { ArrayList<RecommendEntity>() }
    val adapter by lazy { RecommendAdapter(list) }
    val refreshing by lazy { MutableLiveData<Boolean>() }


    init {
        obtainRecommendCode()
        obtainRecommendPerson()
        adapter.emptyView = LayoutInflater.from(App.instance).inflate(R.layout.empty_layout,null)
    }

    fun refreshData() {
        refreshing.value = true
        obtainRecommendCode()
        obtainRecommendPerson()
    }

    private fun obtainRecommendCode() {
        BaseNetCore.ApiServiceImpl.obtainRecommendCode().compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<String>() {
            override fun onSuccess(t: String?) {
                code.value = t
            }

            override fun onFail(code: String) {

            }
        })
    }

    private fun obtainRecommendPerson() {
        BaseNetCore.ApiServiceImpl.obtainRecommendPerson().compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<List<RecommendEntity>>() {
            override fun onSuccess(t: List<RecommendEntity>?) {
                if (!t.isNullOrEmpty()) {
                    list.clear()
                    list.addAll(t)
                    adapter.notifyDataSetChanged()
                }
                if (refreshing.value == true)
                    toast { "刷新成功" }
                refreshing.value = false

            }

            override fun onFail(code: String) {
                if (refreshing.value == true) toast { "刷新失败" }
                refreshing.value = false
            }
        })
    }

}